package com.gl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gl.entity.EduChapter;
import com.gl.entity.EduVideo;
import com.gl.entity.chapterOrVideo.Chapter;
import com.gl.entity.chapterOrVideo.Video;
import com.gl.mapper.EduChapterMapper;
import com.gl.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.service.EduVideoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-12-14
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;

    //根据课程id查询对应的章节小节
    @Override
    public List<Chapter> getChapterVideoByCourseId(String courseId) {
        //根据课程id查出所有章节
        QueryWrapper<EduChapter> wrapperChapter = new QueryWrapper<>();
        wrapperChapter.orderByAsc("gmt_create");
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> eduChapters = baseMapper.selectList(wrapperChapter);
        //根据课程id查出所有小节
        QueryWrapper<EduVideo> wrapperVideo = new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> eduVideos = videoService.list(wrapperVideo);
        //创建最终返回数据的集合
        List<Chapter> list = new ArrayList<>();
        //遍历章节
        for (EduChapter eduChapter : eduChapters) {
            //复制属性值
            Chapter chapter = new Chapter();
            BeanUtils.copyProperties(eduChapter,chapter);
            //添加到集合中
            list.add(chapter);
            //创建章节下的小节集合
            List<Video> videoList = new ArrayList<>();
            //遍历小节，判断其中章节id是不是此次章节遍历的id是便加入到小节集合
            for (EduVideo eduVideo : eduVideos) {
                if(eduVideo.getChapterId().equals(eduChapter.getId())){
                    //复制属性值
                    Video video = new Video();
                    BeanUtils.copyProperties(eduVideo,video);
                    //添加到小节集合
                    videoList.add(video);
                }

            }
            //把章节下对应的小节集合加入
            chapter.setChildren(videoList);
        }


        return list;
    }


}
